package com.blue.http.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blue.core.util.ExceptionUtil;
import com.blue.core.util.JsonUtil;
import com.blue.http.message.WebsocketRequest;
import com.blue.http.message.WebsocketResponse;

/**
 * Websocket 日志工具类
 * 
 * @author zhengj
 * @since 1.0 2016年12月15日
 */
public class WebsocketUtil
{
	private static Logger logger = LoggerFactory.getLogger(WebsocketUtil.class);
	
	public WebsocketUtil()
	{
	}
	
	/**
	 * 通过 Websocket 请求对象创建 Websocket 响应对象
	 * 
	 * @param request Websocket 请求对象
	 * @param responseClazz Websocket 响应类
	 * @return Websocket 响应对象
	 */
	@SuppressWarnings("unchecked")
	public static <T extends WebsocketResponse> T createResponse(WebsocketRequest request, Class<? extends WebsocketResponse> responseClazz)
	{
		T response = null;
		try
		{
			response = (T)responseClazz.newInstance();
			response.setRequestId(request.getRequestId());
			response.setUrl(request.getUrl());
			response.setType(request.getType());
			response.setUserId(request.getUserId());
		}
		catch (Exception e)
		{
			logger.error("创建 Websocket 响应对象失败：" + responseClazz.getName(), e);
		}
		return response;
	}
	
	/**
	 * 记录日志
	 * 
	 * @param request Websocket 请求对象
	 * @param response Websocket 响应类
	 * @param e 抛出的异常
	 */
	public static void log(WebsocketRequest request, WebsocketResponse response, long start, Exception e)
	{
		long used = System.currentTimeMillis() - start;
		if (response.isState()) // 成功
		{
			logger.info("url: {}, request_id: {}, result: 成功, used: {}ms\n请求：{}\n返回: {}", request.getUrl(), request.getRequestId(), used,
					JsonUtil.output(request), JsonUtil.output(response.getResult()));
		}
		else
		{
			if (e instanceof WebsocketException) // 业务异常
			{
				logger.info("url: {}, request_id: {}, result: 失败, used: {}ms\n请求：{}\n错误信息：{}\n返回: {}", request.getUrl(), request.getRequestId(), used,
						JsonUtil.output(request), response.getReason(), JsonUtil.output(response.getResult()));
			}
			else // 系统异常
			{
				logger.info("url: {}, request_id: {}, result: 失败, used: {}ms\n请求：{}\n返回: {}\n错误信息：{}\n异常: {}", request.getUrl(), request.getRequestId(), used,
						JsonUtil.output(request), response.getReason(), JsonUtil.output(response.getResult()), ExceptionUtil.exceptionToString(e, 20));
			}
		}
	}
	
}
